﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace LaunchPad.Core.Controls.Tracks
{
    public partial class PlaybackControl : UserControl
    {
        private double _position;
        private double _center;
        public event EventHandler PositionChanged;

        public double Position
        {
            get
            {
                return _position;
            }

            set
            {
                double adjustedPos = value - _center;

                if (value >= 0)
                {
                    if (_position != value || (double)GetValue(Canvas.LeftProperty) != adjustedPos)
                    {
                        SetValue(Canvas.LeftProperty, adjustedPos);
                        _position = value;
                    }
                }
            }
        }
          
        public PlaybackControl()
        {
            InitializeComponent();
            MouseDown += PlaybackControlMouseDown;
            MouseMove += PlaybackControlMouseMove;
            MouseUp += PlaybackControlMouseUp;
            SizeChanged += PlaybackControlSizeChanged;
        }

        void PlaybackControlSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.WidthChanged)
                _center = e.NewSize.Width / 2;
        }

        void PlaybackControlMouseUp(object sender, MouseButtonEventArgs e)
        {
            if (IsMouseCaptured)
                ReleaseMouseCapture();
        }

        void PlaybackControlMouseMove(object sender, MouseEventArgs e)
        {
            if (IsMouseCaptured)
            {
                Position = e.GetPosition(Parent as Canvas).X;
                if (PositionChanged != null)
                    PositionChanged(this, EventArgs.Empty);
                e.Handled = true;
            }
        }

        void PlaybackControlMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                CaptureMouse();
                e.Handled = true;
            }
        }
    }
}